import Vue from 'vue'
import serverUrl from '../config/base-url'
import moment from 'moment'
let utils = {}

utils.fileSaveAs = (url, params) => {
  let paramsStr = ''
  for (let key in params) {
    if (typeof params[key] === 'object') {
      // 对象类型，需要判断是否有id，并拼接成对应的参数格式
      if (params[key].id) {
        paramsStr = paramsStr + `&${key}.id=${params[key].id}`
      }
    } else {
      paramsStr = paramsStr + `&${key}=${params[key]}`
    }
  }

  if (paramsStr.length > 0) {
    paramsStr = `?${paramsStr.substring(1)}&access_token=${localStorage.appToken}`
  } else {
    paramsStr = `?access_token=${localStorage.appToken}`
  }

  let a = document.createElement('a')
  a.href = `${serverUrl}${url}${paramsStr}`
  a.target = '_blank'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 验证版本名是否合规
utils.nameVerify = (rule, value, callback) => {
  let reg = /[\\/\\:\\*\\?\\"\\<\\>\\|\\\\]/
  if (reg.test(value)) {
    callback(new Error('Special characters are not supported (/\\:*?"<>|) '))
  } else {
    callback()
  }
}

// 解析查询对象及条件配置
utils.parseQueryCondition = (queryModel, queryConfig = []) => {
  const filter = []
  for (const queryKey in queryModel) {
    // right 值
    const queryModelItem = queryModel[queryKey]
    // 查询条件配置
    const queryConfigItem = queryConfig.filter(item => !item.hidden).find(item => item.prop === queryKey) || {}
    // 有forbidden属性不添加查询条件
    if (queryConfigItem.forbidden) {
      continue
    }
    /**
     * 组件配置中包含 operate 属性
     */
    let operate
    switch (queryConfigItem.type) {
      case 'Input':
        operate = queryConfigItem.operate || 'like'
        break
      // 默认为 =
      case 'Select':
        operate = queryConfigItem.operate || '='
        break
      case 'Datepicker':
        operate = queryConfigItem.operate || '='
        break
      // case 'Input':
      //   break
      default:
        operate = queryConfigItem.operate || '='
        break
    }

    if (typeof queryModelItem === 'string' && queryModelItem.length > 0) {
      filter.push({ left: queryKey, operate, right: queryModelItem })
    } else if (queryConfigItem.type === 'Select' && queryConfigItem.component.multiple && queryModelItem.length) {
      filter.push({ left: queryKey, operate: 'in', right: queryModelItem })
    } else if (queryConfigItem.type === 'Datepicker' && queryConfigItem.component && queryConfigItem.component.type && queryConfigItem.component.type.indexOf('range') > -1 && queryModelItem && queryModelItem.length === 2) {
      if (queryConfigItem.component.type === 'monthrange' && queryConfigItem.component.completion) {
        filter.push(
          ...[
            { left: queryKey, operate: '>=', right: queryModelItem[0] + '-01 00:00:00' },
            { left: queryKey, operate: '<=', right: moment(queryModelItem[1]).add(1, 'month').subtract(1, 'seconds').format('YYYY-MM-DD HH:mm:ss') }
          ]
        )
      } else if (queryConfigItem.component.type === 'daterange' && queryConfigItem.component.completion) {
        filter.push(
          ...[
            { left: queryKey, operate: '>=', right: queryModelItem[0] + ' 00:00:00' },
            { left: queryKey, operate: '<=', right: queryModelItem[1] + ' 23:59:59' }
          ]
        )
      } else {
        filter.push(
          ...[
            { left: queryKey, operate: '>=', right: queryModelItem[0] },
            { left: queryKey, operate: '<=', right: queryModelItem[1] }
          ]
        )
      }
    }
  }

  return { filter }
}

utils.parseCompName = (compName, compPrefix = 'el-') => {
  let compNameStr = ''
  if (compName.startsWith(compPrefix)) {
    compNameStr = compName.replace(compPrefix, '').replace(/-/ig, '')
  } else {
    compNameStr = compName.replace('sk-', '').replace(/-/ig, '')
  }
  return compNameStr.toUpperCase()
}

utils.prop2label = (prop) => {
  let str = prop.replace(/([A-Z])/g, ' $1')
  let label = str.substr(0, 1).toUpperCase() + str.substr(1)
  return label
}

utils.getColConfig = (prop) => {
  return {
    prop: prop,
    label: utils.prop2label(prop),
    sortable: 'custom',
    width: prop.length * 8 + 50
  }
}

utils.formatQueryStrToJSON = (queryStr) => {
  let query = {}
  queryStr.split('&').forEach(queryItemStr => {
    const queryNameWithValue = queryItemStr.split('=')
    query[queryNameWithValue[0]] = queryNameWithValue[1]
  })
  return query
}

utils.formatNumberToSpecial = (value, showZeroFlag, showPlusFlag, showPercentFlag, decimal) => {
  // 负数替换成▲
  // 0 替换成 -
  // 千分位
  let format = (num) => {
    return (num.toFixed(decimal !== undefined ? decimal : 2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
  }
  let result = Number(value)
  if (showPercentFlag) {
    result = result * 100
  }
  // result = result.toFixed(decimal !== undefined ? decimal : 2) - 0
  if (result < 0) {
    result = `▲${format(-result)}`
  } else if (result === 0) {
    result = showZeroFlag ? format(result) : '-'
  } else {
    result = (showPlusFlag ? '+' : '') + format(result)
  }
  if (showPercentFlag && result !== '-') {
    result = result + '%'
  }
  return result
}

utils.formatNumberToThousands = (value) => {
  // 负数替换成▲
  // 0 替换成 -
  // 千分位
  let format = (num) => {
    return (num.toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
  }
  let result = Number(value)
  return format(result)
}

utils.stopEditing = (instance) => {
  // 下列这行代码防止点击提交后 没触发编辑状态的组件更新
  instance.gridOptions.api.stopEditing()
  console.log('Ag-Grid is stop editing.')
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, 200)
  })
}
Vue.use({
  install (Vue) {
    // 采用这种方式定义属性，不会被修改和删除
    Object.defineProperty(Vue.prototype, '$utils', { value: utils })
  }
})
